package com.zzedu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.zzedu.common.core.domain.entity.SysUser;
import com.zzedu.common.enums.CommonEnums;
import com.zzedu.common.exception.ServiceException;
import com.zzedu.common.utils.SecurityUtils;
import com.zzedu.common.utils.StringUtils;
import com.zzedu.common.utils.bean.BeanUtils;
import com.zzedu.domain.ZzChargeOrderPay;
import com.zzedu.domain.ZzSchool;
import com.zzedu.dto.ZzChargeOrderPayDTO;
import com.zzedu.mapper.ZzChargeOrderPayMapper;
import com.zzedu.service.IZzChargeOrderPayService;
import com.zzedu.service.IZzSchoolService;
import com.zzedu.system.service.ISysUserService;
import com.zzedu.vo.ZzChargeOrderPayVO;
import com.zzedu.vo.ZzChargeOrderVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * (教育-学校)收费订单_付款Service业务层处理
 *
 * @author Mr.Wang
 * @date 2025-10-18
 */
@Service
public class ZzChargeOrderPayServiceImpl extends ServiceImpl<ZzChargeOrderPayMapper, ZzChargeOrderPay> implements IZzChargeOrderPayService {

    @Autowired
    IZzSchoolService zzSchoolService;

    @Autowired
    ISysUserService sysUserService;


    @Override
    public LambdaQueryWrapper<ZzChargeOrderPay> buildQuery(ZzChargeOrderPayDTO zzChargeOrderPayDTO) {
        LambdaQueryWrapper<ZzChargeOrderPay> lambdaQueryWrapper = Wrappers.lambdaQuery();

        if (CollectionUtils.isNotEmpty(zzChargeOrderPayDTO.getSchoolIdArray())) {
            lambdaQueryWrapper.in(ZzChargeOrderPay::getSchoolId, zzChargeOrderPayDTO.getSchoolIdArray());
        }
        lambdaQueryWrapper.eq(null != zzChargeOrderPayDTO.getPayState(), ZzChargeOrderPay::getPayState, zzChargeOrderPayDTO.getPayState());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(zzChargeOrderPayDTO.getCalcMonth()), ZzChargeOrderPay::getCalcMonth, zzChargeOrderPayDTO.getCalcMonth());

        lambdaQueryWrapper.orderByDesc(ZzChargeOrderPay::getSchoolId).orderByDesc(ZzChargeOrderPay::getRenewType).orderByDesc(ZzChargeOrderPay::getId);

        lambdaQueryWrapper.orderByDesc(ZzChargeOrderPay::getId);
        return lambdaQueryWrapper;
    }

    @Override
    public List<ZzChargeOrderPayVO> convertVO(List<ZzChargeOrderPay> zzChargeOrderList) {
        List<ZzChargeOrderPayVO> list = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(zzChargeOrderList)) {
            for (ZzChargeOrderPay zzChargeOrder : zzChargeOrderList) {
                ZzSchool zzSchool = zzSchoolService.getById(zzChargeOrder.getSchoolId());
                ZzChargeOrderPayVO zzChargeOrderVO = new ZzChargeOrderPayVO();
                BeanUtils.copyBeanProp(zzChargeOrderVO, zzChargeOrder);
                if (null != zzSchool) {
                    zzChargeOrderVO.setSchoolName(zzSchool.getSchoolName());
                }
                if (null != zzChargeOrder.getDoUserId()) {
                    SysUser sysUser = this.sysUserService.getById(zzChargeOrder.getDoUserId());
                    if (null != sysUser) {
                        zzChargeOrderVO.setDoUserName(sysUser.getUserName() + "(" + sysUser.getNickName() + ")");
                    }
                }
                list.add(zzChargeOrderVO);
            }
        }

        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, readOnly = false)
    public String importData(List<ZzChargeOrderVO> zzChargeOrderPayVOS, boolean updateSupport) {
        if (StringUtils.isNull(zzChargeOrderPayVOS) || zzChargeOrderPayVOS.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ZzChargeOrderVO zzChargeOrderPayVO : zzChargeOrderPayVOS) {
            try {
                ZzChargeOrderPay zzChargeOrderPay = new ZzChargeOrderPay();
                BeanUtils.copyBeanProp(zzChargeOrderPay, zzChargeOrderPayVO);
                zzChargeOrderPay.setGmtModify(null);
                zzChargeOrderPay.setReadFlag(CommonEnums.NO.getCode());
                this.saveOrUpdate(zzChargeOrderPay);
                successNum++;
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、 " + zzChargeOrderPayVO.getSchoolName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public boolean confirm(List<Long> ids) {
        List<ZzChargeOrderPay> zzChargeOrderList = this.listByIds(ids);
        for (ZzChargeOrderPay zzChargeOrder : zzChargeOrderList) {
            CommonEnums commonEnums = CommonEnums.getCode(zzChargeOrder.getPayState());
            if (commonEnums == CommonEnums.YES) {
                continue;
            }
            zzChargeOrder.setPayState(CommonEnums.YES.getCode());
            zzChargeOrder.setDoTime(LocalDateTime.now());
            zzChargeOrder.setDoUserId(SecurityUtils.getUserId());
            this.updateById(zzChargeOrder);
            zzSchoolService.update(Wrappers.lambdaUpdate(ZzSchool.class)
                    .eq(ZzSchool::getId, zzChargeOrder.getSchoolId())
                    .set(ZzSchool::getState, CommonEnums.YES.getCode()));
            zzSchoolService.refreshCache(zzChargeOrder.getSchoolId());
        }
        return true;
    }
}